package service

import (
	"astgram/common"
	"astgram/dal/po"
	"astgram/dal/repo"
	"astgram/model"
	"astgram/model/vo"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

type RegService struct {
}

func (ss *RegService) checkParam(c *gin.Context, req *model.RegRequest) error {
	userRepo := repo.NewUserRepo()
	userPo, _ := userRepo.GetUser(repo.GetUserQuery{
		Username: req.Username,
		Pwd:      req.Pwd,
	})
	if userPo != nil {
		return errors.New("该用户名已经存在！")
	}
	return nil
}

func (ss *RegService) Execute(c *gin.Context, req *model.RegRequest) (*model.RegResponse, error) {
	// todo set token
	if err := ss.checkParam(c, req); err != nil {
		return nil, err
	}
	userRepo := repo.NewUserRepo()

	userPo := &po.User{
		Username: req.Username,
		Pwd:      req.Pwd,
		HeadURL:  getRandomHeadURL(),
	}
	err := userRepo.Create(userPo)
	if err != nil {
		return nil, err
	}
	return &model.RegResponse{
		Meta: common.MetaOk,
		User: &vo.User{
			Username: userPo.Username,
			HeadURL:  userPo.HeadURL,
			UserID:   cast.ToInt64(userPo.ID),
		},
	}, nil
}

func getRandomHeadURL() string {
	return "https://cdn.asueeer.com/images/202111/1916298011_1636728808_47.jpeg"
}
